<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字..."></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSave">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pets" :cell-style="{'text-align':'center'}" :header-cell-style="{'text-align':'center'}"
              highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" label="序号" width="60">
      </el-table-column>
      <el-table-column prop="name" label="宠物名称" width="auto" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="售价" width="auto" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本" width="auto" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="auto" sortable>
        <template scope="scope">
          <span v-if="scope.row.state=='0'" style="color: #ff0000">上架</span>
          <span v-if="scope.row.state=='1'" style="color: green">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="type.name" label="宠物类型" min-width="auto" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" min-width="auto" sortable>
      </el-table-column>
      <el-table-column prop="shop.name" label="所属店铺" min-width="auto" sortable>
      </el-table-column>
      <el-table-column prop="user.username" label="领养人" min-width="auto" sortable>
      </el-table-column>
      <el-table-column prop="searchMasterMsgId" label="宠物来源" min-width="auto" sortable>
        <template scope="scope">
          <span v-if="scope.row.searchMasterMsgId" style="color: #ff0000">寻主信息</span>
          <span v-else style="color: green">店铺饲养</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="auto">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row) ">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-button type="danger" @click="onsale" :disabled="this.sels.length===0">批量上架</el-button>
      <el-button type="danger" @click="offsale" :disabled="this.sels.length===0">批量下架</el-button>
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="total"
                     :page-sizes="pageSizes"
                     @size-change="handleSizeChange"
                     :current-page="currentPage"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑/添加界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="宠物售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="宠物成本价" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="0">上架</el-radio>
            <el-radio class="radio" :label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属店铺">

          <!--回显的时候会将saveForm.manager_id的值跟下面managers中每个对象的id进行比对匹配上了就回显
          managers中对象的username-->
          <el-select v-model="saveForm.shopId" placeholder="请选择" clearable>

            <!--v-for="item in managers"-->
            <!--循环managers中的对象-->

            <!--:label="item.username"-->
            <!--回显的数据-->

            <!--:value="item.id"-->
            <!--添加修改时传到后端的数据-->

            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.tel }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-cascader v-model="saveForm.typeId"
                       :options="typeTree"
                       :props="{checkStrictly : true, expandTrigger: 'hover', label:'name',value:'id'}"
                       clearable filterable></el-cascader>
        </el-form-item>

        <el-form-item label="资源" prop="resources">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastdfs"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="简介" prop="intro">
          <quill-editor v-model="saveForm.petDetail.intro" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice">
          <quill-editor v-model="saveForm.petDetail.adoptNotice" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>


  </section>
</template>

<script>
/*import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getPetListPage, removePet, batchRemovePet, editPet, addPet } from '../../api/api';*/

//引入Vue的ueditor的资源
import {quillEditor} from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

export default {
  components: {
    quillEditor
  },
  data() {

    return {
      quillOption: quillConfig,
      fileList: [],

      imgPrefix: 'http://123.207.27.208:80',

      // 分页需要的参数
      pets: [],
      currentPage: 1,
      total: 0,
      pageSize: 5,
      listLoading: false,
      pageSizes: [5, 10, 20, 50],


      // 关键字查询参数
      keyword: '',


      // 批量删除参数
      sels: [],//列表选中列


      saveFormVisible: false,//编辑界面是否显示
      saveLoading: false,
      saveFormRules: {
        name: [
          {required: true, message: '请输入宠物名称', trigger: 'blur'}
        ],
        saleprice: [
          {required: true, message: '请输入宠物售价', trigger: 'blur'}
        ],
        costprice: [
          {required: true, message: '请输入宠物成本价', trigger: 'blur'}
        ],
      },
      //编辑界面数据
      title: '',
      saveForm: {
        id: null,
        name: '',
        saleprice: '',
        costprice: '',
        resources: '',
        state: '',
        typeId: '',
        type: null,
        offsaletime: '',
        onsaletime: '',
        createtime: '',
        shopId: '',
        shop: null,
        userId: '',
        user: null,
        searchMasterMsgId: '',
        petDetail: {  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        },
      },

      // 添加修改时  宠物经理下拉框需要的数据
      shops: [],

      // 宠物树需要的数据
      typeTree: [],
    }
  },
  methods: {
    //获取宠物列表
    getPets() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword,
      };
      this.listLoading = true;
      //NProgress.start();
      this.$http.post("/pet", para).then((res) => {
        this.total = res.data.totals;
        this.pets = res.data.data;
        this.listLoading = false;
        //NProgress.done();
      }).catch(res => {
        this.$notify({
          title: '错误',
          duration: 1000,
          showClose: true,
          message: '系统繁忙，请稍后再试！',
          type: 'error'
        });
      });
    },


    // 添加或修改时  获取宠物经理的下拉菜单中需要的值
    getShops() {
      this.$http.get("/shop").then(res => {
        this.shops = res.data;
      }).catch(res => {

      })
    },

    // 添加或修改时  获取下拉菜单中需要的值
    getTypeTree() {
      this.$http.get("/petType/petTypeTree").then(res => {
        this.typeTree = res.data
      }).catch(res => {

      })

    },


    // 高级查询
    keywordQuery() {
      this.currentPage = 1;
      this.getPets();
    },

    // 当前页改变时
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPets();
    },

    // 每页显示数量改变时
    handleSizeChange(val) {
      this.pageSize = val;
      this.getPets();
    },

    //删除单条数据
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const id = row.id;
        this.$http.delete("/pet/" + id).then(res => {
          if (res.data.success) {
            // 如果删除的数据是当前页的最后一条 删除后就显示当前数据的最后一页
            console.log(this.total)
            console.log(this.currentPage)
            console.log(this.pageSize)
            if ((this.total - 1) % this.pageSize == 0 && this.currentPage == (this.total - 1) / this.pageSize + 1 && this.currentPage > 1) {
              this.currentPage = this.currentPage - 1
            }
            console.log((this.total - 1) % this.pageSize)
            this.getPets();
            console.log(this.total)
            console.log(this.currentPage)
            console.log(this.pageSize)
            this.$notify({
              title: '成功',
              duration: 2000,
              showClose: true,
              message: '删除成功！',
              type: 'success'
            });
          } else {
            this.$notify({
              title: '错误',
              duration: 2000,
              showClose: true,
              message: '系统繁忙(500)，请稍后再试！',
              type: 'error'
            });
          }
        }).catch(res => {
          this.$notify({
            title: '失败',
            duration: 2000,
            showClose: true,
            message: '系统繁忙(404/400)，请稍后再试！',
            type: 'error'
          });
        })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleSave: function (index, row) {
      this.getShops()
      this.getTypeTree()
      if (row == null) {
        this.title = "添加"
        this.saveForm = {
          id: null,
          name: '',
          saleprice: '',
          costprice: '',
          resources: '',
          state: 0,
          typeId: '',
          offsaletime: '',
          onsaletime: '',
          createtime: '',
          shopId: '',
          userId: '',
          searchMasterMsgId: '',
          petDetail: {  //与后端实体类一致
            intro: '',
            adoptNotice: ''
          }
        }

        this.fileList = []
        this.saveFormVisible = true;
      } else {
        this.title = "修改"
        this.saveFormVisible = true;
        this.saveForm = Object.assign({}, row);
        console.log(this.saveForm)
        //图片回显
        this.fileList = [];
        if (this.saveForm.resources) {//有值
          let arr = this.saveForm.resources.split(",");
          for (var i = 0; i < arr.length; i++) {
            this.fileList.push({"url": this.imgPrefix + arr[i]});
          }
        }

      }
    },

    //新增或编辑一条数据后保存
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            //NProgress.start();


            //console.log(JSON.parse(JSON.stringify(this.saveForm.parent_id))[length])
            let para = Object.assign({}, this.saveForm);
            console.log(para)
            if (isNaN(para.typeId)) {
              para.typeId = para.typeId[para.typeId.length - 1]
            }
            if (para.parent_id != null) {
              para.parent_id = para.parent_id[para.parent_id.length - 1]
            }
            this.$http.put("/pet", para).then(res => {
              if (res.data.success) {
                this.saveFormVisible = false,//编辑界面是否显示
                    this.saveLoading = false,
                    this.getPets();
                this.$notify({
                  title: '成功',
                  duration: 2000,
                  showClose: true,
                  message: '操作成功！',
                  type: 'success'
                });

              } else {
                this.$notify({
                  title: '错误',
                  duration: 2000,
                  showClose: true,
                  message: '系统繁忙(500)，请稍后再试！',
                  type: 'error'
                });
              }
            }).catch(res => {
              this.$notify({
                title: '失败',
                duration: 2000,
                showClose: true,
                message: '系统繁忙(404/400)，请稍后再试！',
                type: 'error'
              });
            })
          }).catch(() => {

          });
        }
      });
    },

    // 多选数据改变时
    selsChange: function (sels) {
      console.log(sels)
      this.sels = sels;
    },

    //批量删除数据
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/pet/", ids).then(res => {
          if (res.data.success) {
            // 如果删除的数据是当前页的最后一条 删除后就显示当前数据的最后一页
            if ((this.total - this.sels.length) % this.pageSize == 0 && this.currentPage == (this.total - this.sels.length) / this.pageSize + 1 && this.currentPage > 1) {
              this.currentPage = this.currentPage - 1
            }
            this.getPets();
            this.$notify({
              title: '成功',
              duration: 2000,
              showClose: true,
              message: '删除成功！',
              type: 'success'
            });
          } else {
            this.$notify({
              title: '错误',
              duration: 2000,
              showClose: true,
              message: '系统繁忙(500)，请稍后再试！',
              type: 'error'
            });
          }
        }).catch(res => {
          this.$notify({
            title: '失败',
            duration: 2000,
            showClose: true,
            message: '系统繁忙(404/400)，请稍后再试！',
            type: 'error'
          });
        })
      }).catch(() => {

      });
    },
    //文件上传的业务逻辑
    handleSuccess(response, file, fileList) {
      if (this.saveForm.resources) {
        this.saveForm.resources = this.saveForm.resources + "," + response.resultObj;
      } else {
        this.saveForm.resources = response.resultObj;
      }
      this.fileList = [];//清空
      if (this.saveForm.resources) {
        var Arr = this.saveForm.resources.split(",");
        for (var i = 0; i < Arr.length; i++) {
          this.fileList.push({url: this.imgPrefix + Arr[i]})
        }
      }
    },

    //文件删除的业务逻辑
    handleRemove(file, fileList) {
      var filePath = file.url;
      // 去掉前面的前缀
      var path = filePath.substring(filePath.indexOf("/group"));
      this.$http.delete("/fastdfs/?path=" + path).then(res => {
        if (res.data.success) {
          this.$notify({
            title: '成功',
            duration: 2000,
            showClose: true,
            message: '删除成功！',
            type: 'success'
          });
        } else {
          this.$notify({
            title: '成功',
            duration: 2000,
            showClose: true,
            message: '删除失败！',
            type: 'error'
          });
        }
      })


      if (this.saveForm.resources) {

        var pathArr = this.saveForm.resources.split(",");
        for (var i = 0; i < pathArr.length; i++) {
          var pathTemp = pathArr[i];
          if (pathTemp == path) { //你要删除的图片找到了
            //从下标为i的地方开始删除，删1个
            pathArr.splice(i, 1);
            break;
          }
        }
        this.saveForm.resources = pathArr.join(",");
      }

      //处理页面回显
      this.fileList = [];//清空
      if (this.saveForm.resources) {
        var Arr = this.saveForm.resources.split(",");
        for (var i = 0; i < Arr.length; i++) {
          this.fileList.push({url: this.imgPrefix + Arr[i]})
        }
      }
    },
    onsale() {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/pet/onsale", ids).then(res => {
          if (res.data.success) {
            // 如果删除的数据是当前页的最后一条 删除后就显示当前数据的最后一页
            if ((this.total - this.sels.length) % this.pageSize == 0 && this.currentPage == (this.total - this.sels.length) / this.pageSize + 1 && this.currentPage > 1) {
              this.currentPage = this.currentPage - 1
            }
            this.getPets();
            this.$notify({
              title: '成功',
              duration: 2000,
              showClose: true,
              message: '上架成功！',
              type: 'success'
            });
          } else {
            this.$notify({
              title: '错误',
              duration: 2000,
              showClose: true,
              message: '系统繁忙(500)，请稍后再试！',
              type: 'error'
            });
          }
        }).catch(res => {
          this.$notify({
            title: '失败',
            duration: 2000,
            showClose: true,
            message: '系统繁忙(404/400)，请稍后再试！',
            type: 'error'
          });
        })
      }).catch(() => {

      });
    },
    offsale() {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/pet/offsale", ids).then(res => {
          if (res.data.success) {
            // 如果删除的数据是当前页的最后一条 删除后就显示当前数据的最后一页
            if ((this.total - this.sels.length) % this.pageSize == 0 && this.currentPage == (this.total - this.sels.length) / this.pageSize + 1 && this.currentPage > 1) {
              this.currentPage = this.currentPage - 1
            }
            this.getPets();
            this.$notify({
              title: '成功',
              duration: 2000,
              showClose: true,
              message: '下架成功！',
              type: 'success'
            });
          } else {
            this.$notify({
              title: '错误',
              duration: 2000,
              showClose: true,
              message: '系统繁忙(500)，请稍后再试！',
              type: 'error'
            });
          }
        }).catch(res => {
          this.$notify({
            title: '失败',
            duration: 2000,
            showClose: true,
            message: '系统繁忙(404/400)，请稍后再试！',
            type: 'error'
          });
        })
      }).catch(() => {

      });
    },

  },

  // 页面加载时
  mounted() {
    this.getPets();
  }
}

</script>

<style scoped>

</style>
